package itbour.onetouchshow.activity.video.tableedit;


import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import itbour.onetouchshow.R;
import itbour.onetouchshow.adapter.TableAdapter;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.bean.inching.noppt.NoPPTRootTableValueV10Bean;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.listener.SoftKeyBoardListener;
import itbour.onetouchshow.singlecase.InchingDataSingleCase;
import itbour.onetouchshow.utils.FineTuneRender;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.widget.inching.GridViewInHorizonScrollView;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class TableeditActivity extends MVPBaseActivity<TableeditContract.View, TableeditPresenter> implements TableeditContract.View {

    @BindView(R.id.grid_view)
    GridViewInHorizonScrollView gridView;
    @BindView(R.id.hs)
    HorizontalScrollView hs;
    @BindView(R.id.confirmBTN)
    RelativeLayout confirmBtn;

    @BindView(R.id.rl_bottom_padding)
    RelativeLayout bottom_padding;

    @BindView(R.id.ll_bottom_bottom_padding)
    LinearLayout bottom_padding_padding;
    Integer defalutWidth = UIUtils.dp2px(150);
    private PopupWindow pw;
    private TableAdapter adapter;
    private ArrayList<ArrayList<String>> mData;
    private int pageIndex;
    private int objId;

    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_table_edit;
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        setTitleText("修改表格");
        getToolBarView().setRightImageResource(getResources().getDrawable(R.drawable.delete_gray)).
                setRightImageVisible().setRightIocnOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        }).getLeftimageView().setVisibility(View.GONE);
    }

    private void initKeyBroadListener() {
        SoftKeyBoardListener.setListener(TableeditActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {

                L_.i("键盘显示 高度" + height);
                bottom_padding.setVisibility(View.GONE);
                bottom_padding_padding.setVisibility(View.GONE);
            }

            @Override
            public void keyBoardHide(int height) {
                L_.i("键盘隐藏 高度" + height);
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        bottom_padding.setVisibility(View.VISIBLE);
                        bottom_padding_padding.setVisibility(View.VISIBLE);
                    }
                }, 200);
            }
        });
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        initKeyBroadListener();
        //初始化该控件
        pw = initPopWindow();


        Intent intent = getIntent();
        pageIndex = intent.getIntExtra("pageIndex", -1);
        objId = intent.getIntExtra("objId", -1);

        ArrayList<ArrayList<String>> nowTableData = InchingDataSingleCase.INSTANCE.getNowTableData();
        mData = nowTableData;

//        NoPPTRootTableValueV10Bean value = InchingDataSingleCase.INSTANCE.getTableData();
//        //设置rowtype标记表头
//        value.refreshCellTextRowType();
//        InchingCoreRootNoPPTV10Bean tableCoreData = InchingDataSingleCase.INSTANCE.getTableDaGangData();
//        //刷新pageIndexAndObjList
////        tableCoreData.refreshTableData();
//
//        List<NoPPTRootTableValueV10Bean.RootTableValueV10RowBean> tableRowList = value.children;
//        int colmnsCount = tableRowList.get(0).children.size();
//
//        List<InchingRelationsV10Bean> relations = tableCoreData.getRelations();
//        InchingDocStringNoPPTV10Bean.CoreStructureBean coreStructure = InchingDataSingleCase.INSTANCE.getInstance().getCoreStructure();
//        ArrayList<Integer> page_indexList = coreStructure.getRoot().getPageIndexOrObjIdList(tableCoreData, AppConst.PAGEINDEXTAG, coreStructure.getVersion());
//        ArrayList<Integer> obj_idList = coreStructure.getRoot().getPageIndexOrObjIdList(tableCoreData, AppConst.OBJIDTAG, coreStructure.getVersion());
//
        adapter = new TableAdapter(this, nowTableData);
        adapter.setDateChangeLisener(new TableAdapter.GriddataChangeLisener() {

            @Override
            public void dataChangeFrom(Integer row, Integer column, String text) {
//                Toast.makeText(mContext, "行" + row + "列" + column + text, Toast.LENGTH_LONG).show();

            }

            //长按
            @Override
            public void rowAndColumnManupulate(Integer row, Integer column, View v) {
                showPopupWindow(v, pw, row, column, adapter, gridView, nowTableData, adapter);
            }


        });
//
        gridView.setAdapter(adapter);
        if (nowTableData.size() > 0) {
            refreshTableColumns(nowTableData.get(0).size(), gridView, adapter);
        }
//
//
        // 初始化确认按钮
        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                String str =   value.getResultStringArra().toString() ;
                String value = getTableJson();


                //发送一个eventBus去更新inching中的数据
                long isSuccess = FineTuneRender.changeTableTextForJava(pageIndex, objId, adapter.getRawCount(), adapter.getColumnsCount(), value);
                L_.i("isSuccess===" + isSuccess);


                UIUtils.hideKeyboard(adapter.nowFocus);
                InchingDataSingleCase.INSTANCE.clearSaveTableData();
                EventBus.getDefault().post(AppConst.REFRESH_TABLE);
                finish();
            }
        });

    }

    //
    public PopupWindow initPopWindow() {
        //初始化DragSortGridLayout
        View inflate = View.inflate(this, R.layout.table_longtouch_popwindow, null);
        final PopupWindow pw = new PopupWindow(inflate, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        pw.setWidth(UIUtils.dp2px(300));
        pw.setHeight(UIUtils.dp2px(38));
        pw.setFocusable(true);
        pw.setBackgroundDrawable(new ColorDrawable());


        return pw;
    }

    private void refreshTableColumns(int colmnsCount, GridViewInHorizonScrollView gridView, TableAdapter adapter) {
        RelativeLayout.LayoutParams linearParams = new RelativeLayout.LayoutParams(defalutWidth * colmnsCount, ViewGroup.LayoutParams.WRAP_CONTENT);
        gridView.setLayoutParams(linearParams);
        gridView.setNumColumns(colmnsCount);
        adapter.notifyDataSetChanged();
    }

    //
    public void showPopupWindow(View v, final PopupWindow pw,
                                final Integer row,
                                final Integer column, final TableAdapter adapter, final GridViewInHorizonScrollView gridView,
                                ArrayList<ArrayList<String>> data, final TableAdapter tableAdapter) {
        pw.setOnDismissListener(null);
        //设置pw背景
        pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //popWindow消失，移除背景
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
                tableAdapter.updateHightInformation();
            }

        });
        View inflate = pw.getContentView();
        TextView tv_add_colmns = inflate.findViewById(R.id.tv_add_colmns);
        TextView tv_add_raw = inflate.findViewById(R.id.tv_add_raw);
        TextView tv_delete_colmns = inflate.findViewById(R.id.tv_delete_colmns);
        TextView tv_delete_raw = inflate.findViewById(R.id.tv_delete_raw);

//        TextView tv_paste = (TextView) inflate.findViewById(R.id.tv_paste);
//        TextView tv_copy = (TextView) inflate.findViewById(R.id.tv_copy);
//

        tv_add_colmns.setOnClickListener(null);
        tv_add_raw.setOnClickListener(null);
        tv_delete_colmns.setOnClickListener(null);
        tv_delete_raw.setOnClickListener(null);

//        tv_copy.setOnClickListener(null);
//        tv_paste.setOnClickListener(null);

//        tv_copy.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                LogControl.i(TAG,"tv_copy");
//            }
//        });
//
//        tv_paste.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                LogControl.i(TAG,"tv_paste");
//            }
//        });


        // 添加列
        tv_add_colmns.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pw.dismiss();
                int newColumnsSize = data.get(0).size();
                int tableMaxCol = InchingDataSingleCase.INSTANCE.getLengthControl().getTableMaxCol();
                Log.e("max col is", "" + tableMaxCol);
                if (newColumnsSize < tableMaxCol) {
                    // 在当前列后加列(由于微调库与数据模型插入列列号需一致, 故提出到此位置)
                    int columnIndex = column.intValue() + 1;
                    addColumnPosition(columnIndex);

//                    dataCoreStructureRootBean.refreshTableData();
                    adapter.refreshData();
                    int newColumnsSize1 = data.get(0).size();
                    refreshTableColumns(newColumnsSize1, gridView, adapter);
                } else {
                    T_.showToastReal("不能添加更多列数");
                }

            }
        });
        // 添加行
        tv_add_raw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pw.dismiss();
                int newRawSize = data.size();

                //todo: 未完成
                int tableMaxRow = InchingDataSingleCase.INSTANCE.getLengthControl().getTableMaxRow();
                Log.e("max row is", "" + tableMaxRow);
                if (newRawSize < tableMaxRow) {
                    // 在当前行后加入行
                    int rowIndex = row + 1;
                    addRowPosition(rowIndex);
//                    dataCoreStructureRootBean.refreshTableData();
                    adapter.refreshData();
                    adapter.notifyDataSetChanged();
                } else {
                    T_.showToastReal("不能添加更多行数");

                }
            }
        });
        // 删除列
        tv_delete_colmns.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pw.dismiss();
                int newColumnsSize1 = data.get(0).size();
                if (newColumnsSize1 <= 1) {
                    T_.showToastReal("已经是最小列数");
                } else {
                    removeColumnPosition(column);
                    adapter.refreshData();
                    int newColumnsSize = data.get(0).size();
                    refreshTableColumns(newColumnsSize, gridView, adapter);
                }
            }
        });
        // 删除行
        tv_delete_raw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pw.dismiss();
                int newRawSize = data.size();

                if (newRawSize <= 1) {
                    T_.showToastReal("已经是最小行数");

                } else {
                    removeRawPosition(row);
                    adapter.refreshData();
                    adapter.notifyDataSetChanged();
                }
            }
        });

        int[] location = new int[2];
        v.getLocationInWindow(location);

        int anInt = UIUtils.dp2px(36) * 5 / 6;

        int x = location[0];
        int y = location[1];

        pw.showAtLocation(v, Gravity.TOP, 0, y + anInt);

    }

    // 增删改查

    private void addColumnPosition(int index) {
        for (ArrayList<String> arra : mData) {
            arra.add(index, "");
        }
    }

    private void removeRawPosition(int index) {
        mData.remove(index);
        Log.e("kakaka", "sdf");
    }


    private void addRowPosition(int index) {
        int column = mData.get(0).size();
        ArrayList<String> arra = new ArrayList<>();
        for (int i = 0; i < column; i++) {
            String str = "";
            arra.add(str);
        }
        mData.add(index, arra);
    }


    private void removeColumnPosition(int index) {
        for (ArrayList<String> arra : mData) {
            arra.remove(index);
        }
    }


    public int getNewRawSize(NoPPTRootTableValueV10Bean value) {
        List<NoPPTRootTableValueV10Bean.RootTableValueV10RowBean> children = value.children;
        if (children == null) {
            return 0;
        }
        return children.size();
    }


    public int getNewColumnsSize(NoPPTRootTableValueV10Bean value) {
        List<NoPPTRootTableValueV10Bean.RootTableValueV10RowBean> children = value.children;
        if (children != null && children.size() != 0) {
            return children.get(0).children.size();
        }
        return 0;

    }

    public String getTableJson() {
        //
        ArrayList<String> list = new ArrayList<String>();
        if (mData != null) {
            for (int i = 0; i < mData.size(); i++) {
                ArrayList<String> child = mData.get(i);
                if (child != null) {
                    for (int j = 0; j < child.size(); j++) {
                        String s = child.get(j);
                        list.add(s);
                    }
                }

            }
        }
        return new Gson().toJson(list);
    }
}
